package com.hww.common.util;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.hww.common.dialog.CommonDialog;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 动态权限管理工具类（支持Activity/Fragment、自动回调处理、内存安全）
 * 特性：
 * 1. 自动处理权限授予/拒绝/永久拒绝状态
 * 2. 支持动态权限解释对话框
 * 3. 跳转系统设置页引导用户手动授权
 * 4. 线程安全的请求码分配机制
 * 5. 兼容Android 6.0+系统
 */
public class PermissionUtils {
    /*生成唯一的权限请求码（Request Code），用于标识每一次独立的权限请求。通过原子操作保证多线程环境下的线程安全,设置初始值为5000*/
    private static final AtomicInteger REQUEST_CODE_GENERATOR = new AtomicInteger(5000);
    private static final ConcurrentHashMap<Integer, PermissionCallback> CALLBACK_MAP = new ConcurrentHashMap<>();
    private static WeakReference<Activity> activityRef;
    private static WeakReference<androidx.fragment.app.Fragment> fragmentRef;

    // 初始化Activity上下文
    public static void init(Activity activity) {
        activityRef = new WeakReference<>(activity);
        fragmentRef = null;
    }

    // 初始化Fragment上下文
    public static void init(androidx.fragment.app.Fragment fragment) {
        fragmentRef = new WeakReference<>(fragment);
        activityRef = null;
    }

    /**
     * 检查单个权限是否已授予
     */
    public static boolean checkPermission(Context context, String permission) {
        return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED;
    }

    /**
     * 批量检查权限状态
     *
     * @return 未授权的权限列表
     */
    public static List<String> checkPermissions(Context context, String... permissions) {
        List<String> deniedList = new ArrayList<>();
        for (String perm : permissions) {
            if (!checkPermission(context, perm)) {
                deniedList.add(perm);
            }
        }
        return deniedList;
    }

    /**
     * 请求权限（带动态解释对话框）
     *
     * @param rationale 权限说明文案（可为null）
     */
    public static void requestPermission(String rationale, final String permission, PermissionCallback callback) {
        Context context = getContext();
        if (context == null) {
            return;
        }

        if (checkPermission(context, permission)) {
            callback.onGranted(new String[]{permission});
            return;
        }

        final int requestCode = REQUEST_CODE_GENERATOR.getAndIncrement();
        CALLBACK_MAP.put(requestCode, callback);

        if (ActivityCompat.shouldShowRequestPermissionRationale(getHostActivity(), permission) && rationale != null) {
            showRationaleDialog(context, rationale, new Runnable() {
                @Override
                public void run() {
                    doRequest(requestCode, permission);
                }
            });
        } else {
            doRequest(requestCode, permission);
        }
    }

    /**
     * 批量请求权限（自动处理分组）
     */
    public static void requestPermissions(String rationale, String[] permissions, PermissionCallback callback) {
        Context context = getContext();
        if (context == null) {
            return;
        }

        final List<String> deniedList = checkPermissions(context, permissions);
        if (deniedList.isEmpty()) {
            callback.onGranted(permissions);
            return;
        }

        final int requestCode = REQUEST_CODE_GENERATOR.getAndIncrement();
        CALLBACK_MAP.put(requestCode, callback);

        if (shouldShowRationale(deniedList.get(0)) && rationale != null) {
            showRationaleDialog(context, rationale, new Runnable() {
                @Override
                public void run() {
                    doBatchRequest(requestCode, deniedList);
                }
            });
        } else {
            doBatchRequest(requestCode, deniedList);
        }
    }

    /**
     * 处理权限请求结果（必须在Activity/Fragment的onRequestPermissionsResult 中调用）
     * {@link androidx.fragment.app.FragmentActivity#onRequestPermissionsResult(int, String[], int[])}
     */
    public static void handleResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        PermissionCallback callback = CALLBACK_MAP.remove(requestCode);
        if (callback == null) {
            return;
        }

        List<String> grantedList = new ArrayList<>();
        List<String> deniedList = new ArrayList<>();
        List<String> permanentDenialList = new ArrayList<>();

        for (int i = 0; i < grantResults.length; i++) {
            if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                grantedList.add(permissions[i]);
            } else {
                if (shouldShowRationale(permissions[i])) {
                    deniedList.add(permissions[i]);
                } else {
                    permanentDenialList.add(permissions[i]);
                }
            }
        }

        if (!grantedList.isEmpty()) {
            callback.onGranted(grantedList.toArray(new String[0]));
        }
        if (!deniedList.isEmpty()) {
            callback.onDenied(deniedList.toArray(new String[0]));
        }
        if (!permanentDenialList.isEmpty()) {
            callback.onPermanentDenial(permanentDenialList.toArray(new String[0]));
            showSystemSettingDialog();
        }
    }

    // 显示权限解释对话框
    private static void showRationaleDialog(Context context, String message, final Runnable positiveAction) {
        new AlertDialog.Builder(context)
                .setTitle("权限说明")
                .setMessage(message)
                .setPositiveButton("继续", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        positiveAction.run();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .show();
    }

    // 显示系统设置引导对话框
    private static void showSystemSettingDialog() {
        final Context context = getContext();
        if (context == null) {
            return;
        }

        CommonDialog commonDialog = new CommonDialog(context);
        commonDialog.setTitle("权限被永久拒绝")
                .setMessage("请前往设置手动开启权限")
                .setSingle(true)
                .setPositive("去设置")
                .setNegative("取消")
                .setOnClickBottomListener(new CommonDialog.OnClickBottomListener() {
                    @Override
                    public void onPositiveClick() {
                        /*ToastUtils.success(MyAppThis.getThis(), "点击了确定按钮").show();*/
                        /*openAppDetails(context);*/
                        toAppSetting(context);
                    }
                    @Override
                    public void onNegativeClick() {
                    }
                }).show();
    }

    // 跳转应用详情页
    public static void openAppDetails(Context context) {
        try {
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.parse("package:" + context.getPackageName()));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (Exception e) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS);
            context.startActivity(intent);
        }
    }

    /**
     * 跳转到权限设置界面
     */
    public static void toAppSetting(Context context) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.setData(Uri.fromParts("package", context.getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            intent.setAction(Intent.ACTION_VIEW);
            intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            intent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
        }
        context.startActivity(intent);
    }

    // 执行单个权限请求
    private static void doRequest(int requestCode, String permission) {
        if (fragmentRef != null && fragmentRef.get() != null) {
            fragmentRef.get().requestPermissions(new String[]{permission}, requestCode);
        } else if (activityRef != null && activityRef.get() != null) {
            ActivityCompat.requestPermissions(activityRef.get(), new String[]{permission}, requestCode);
        }
    }

    // 执行批量权限请求
    private static void doBatchRequest(int requestCode, List<String> permissions) {
        String[] perms = permissions.toArray(new String[0]);
        if (fragmentRef != null && fragmentRef.get() != null) {
            fragmentRef.get().requestPermissions(perms, requestCode);
        } else if (activityRef != null && activityRef.get() != null) {
            ActivityCompat.requestPermissions(activityRef.get(), perms, requestCode);
        }
    }

    // 判断是否显示权限解释
    private static boolean shouldShowRationale(String permission) {
        Activity activity = getHostActivity();
        if (activity == null) {
            return false;
        }
        return ActivityCompat.shouldShowRequestPermissionRationale(activity, permission);
    }

    @Nullable
    private static Context getContext() {
        return fragmentRef != null ? fragmentRef.get() != null ? fragmentRef.get().requireContext() : null :
                activityRef != null ? activityRef.get() : null;
    }

    @Nullable
    private static Activity getHostActivity() {
        return fragmentRef != null ? fragmentRef.get() != null ? fragmentRef.get().getActivity() : null :
                activityRef != null ? activityRef.get() : null;
    }

    /**
     * 增强型权限回调接口
     */
    public interface PermissionCallback {
        /**
         * 用户明确授予请求的权限
         *
         * @param grantedPermissions 被成功授予的权限数组（如{Manifest.permission.CAMERA}）
         */
        void onGranted(String[] grantedPermissions);

        /**
         * 用户拒绝权限但未勾选"不再询问"
         *
         * @param deniedPermissions 权限数组
         */
        void onDenied(String[] deniedPermissions);

        /**
         * 用户勾选"不再询问"后拒绝
         *
         * @param permanentDenials 必须引导用户前往系统设置的权限数组
         */
        void onPermanentDenial(String[] permanentDenials);
    }
}